<template>
	<view class="wrap">
		<u-navbar back-icon-color='#fff' title-bold title-color="#fff" title="首页" :is-back="false"
			:background="background">
			<view class="slot-wrap" v-if="this.showIcon">
				<u-icon size="42" name="home" @click="navTo()"></u-icon>
			</view>
		</u-navbar>
		<Search @search-data="handleSearchData" v-show="false" />

		<scroll-view scroll-y="true">
			<!-- 轮播+入口模块 -->
			<view class="container">
				<swiperMain :swiperList="swiperList" :commonList="commonList"></swiperMain>
			</view>
			<hr class="divider">
			<!-- 主要数据 -->
			<view class="container">
				<indexTitle :title1="'指标'" :title2="'统计'"></indexTitle>
				<mainData :homeData="homeData" :formattedTime="formattedTime"></mainData>
			</view>
			<hr class="divider">
			<!-- 水质模块 -->
			<view class="container">
				<indexTitle :title1="'水质'" :title2="'监测'"></indexTitle>
				<waterQuailty v-if="inflowWater.length > 0" :outWater="outWater" :inflowWater="inflowWater"
					:formattedTime="formattedTime" :active="activeSection3" ref='child'></waterQuailty>
			</view>
			<hr class="divider">
			<!-- 事件报警响应率 -->
			<view class="container">
				<indexTitle :title1="'今日报警'" :title2="'响应率'"></indexTitle>
				<view class="charts-box">
					<l-echart style="width:100%;" ref="chartRef" @finished="init()"></l-echart>
				</view>
			</view>
			<hr class="divider">
			<!-- 工单报警响应率 -->
			<view class="container">
				<indexTitle :title1="'今日工单'" :title2="'响应率'"></indexTitle>
				<view class="charts-box">
					<l-echart style="width:100%;" ref="chartRef1" @finished="init()"></l-echart>
				</view>
			</view>
			<hr class="divider">
			<!-- 设备运行状态 -->
			<view class="container">
				<indexTitle :title1="'设备运行'" :title2="'状态'"></indexTitle>
				<view class="charts-box" style="height:320px">
					<qiun-data-charts type="ring" :opts="ringOpt" :chartData="chartData" />
				</view>
			</view>

		</scroll-view>

	</view>
</template>

<script>
	// import * as echarts from '@/uni_modules/lime-echart/static/echarts.min.js';
	import Search from '@/components/headsearch/search.vue'
	import config from '@/common/config.js';
	import swiperMain from '@/pages/sys/index/index/components/swiperMain.vue';
	import mainData from '@/pages/sys/index/index/components/mainData.vue';
	import waterQuailty from '@/pages/sys/index/index/components/waterQuailty.vue';
	import indexTitle from '@/components/title/indexTitle.vue'

	export default {
		components: {
			Search,
			swiperMain,
			mainData,
			waterQuailty,
			indexTitle
		},

		data() {
			return {
				activeSection3: "section3",
				formattedTime: this.getFormattedTime(),
				background: {
					backgroundColor: 'rgb(15, 110, 255)'
				},
				commonList: [{
						url: "/pages/sys/index/liveVideo",
						iconName: '/static/index/liveVideo.png',
						title: '视频监控',
					},
					{
						url: "/pages/sys/news/newList",
						iconName: '/static/index/newList.png',
						title: '新闻公告',
					},
					{
						url: "/pages/sys/alarm/index",
						iconName:'/static/index/alarmCenter.png',
						title: '报警中心',
					},
					{
						url: "/pages/sys/eventwororder/adddeclaration/adddeclaration",
						iconName: '/static/index/declaration.png',
						title: '事件申报',
					}
				],
				showIcon: true,
				swiperList: [],
				homeData: {},
				//厂站
				searchData: '', // 用于保存接收到的数据
				//进水水质
				inflowWater: [],
				//出水水质
				outWater: [],
				//orderEcharts
				alarmChart: '',
				thingOrderChart: '',
				option: {
					title: [{
						text: 12312 + '个',
						subtext: '已响应',
						textStyle: {
							fontSize: 18,
							color: 'red',
						},
						subtextStyle: {
							fontSize: 14,
							color: "#333",
						},
						textAlign: "center",
						x: '18.5%',
						y: '28%',
					}],

					legend: {
						type: "scroll",
						orient: 'vertical',
						left: '50%',
						top: '20%',
						textStyle: {
							color: '#595959'
						},
					},
					series: [{
						name: '标题',
						type: 'pie',
						center: ['20%', '40%'],
						radius: ['55%', '70%'],
						avoidLabelOverlap: false,
						label: {
							show: false,
						},
						emphasis: {
							label: {
								show: false,
							}
						},
						labelLine: {
							show: false
						},
						data: [],
					}]

				},
				option2: {
					// textStyle: {
					// 	fontFamily: "DingTalk JinBuTi"
					// },
					title: [{
						text: 12312 + '个',
						subtext: '已响应',
						textStyle: {
							fontSize: 18,
							color: 'red',
						},
						subtextStyle: {
							fontSize: 14,
							color: "#333"
						},
						textAlign: "center",
						x: '18.5%',
						y: '28%',
					}],

					legend: {
						type: "scroll",
						orient: 'vertical',
						left: '50%',
						top: '20%',
						textStyle: {
							color: '#595959',
						},
					},
					series: [{
						name: '标题',
						type: 'pie',
						center: ['20%', '40%'],
						radius: ['55%', '70%'],
						avoidLabelOverlap: false,
						label: {
							show: false,
						},
						emphasis: {
							label: {
								show: false,
							}
						},
						labelLine: {
							show: false
						},
						data: [],
					}]

				},
				//equipUcharts
				chartData: {},
				ringOpt: {
					// textStyle: {
					// 	fontFamily: "DingTalk JinBuTi"
					// },
					color: ["#91CB74", "#EE6666", "#73C0DE", "#FAC858", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [-40, 5, 5, 5],
					enableScroll: false,
					extra: {
						ring: {
							// fontfamily: HanChanBanYua,
							ringWidth: 50,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 10,
							border: true,
							borderWidth: 3,
							borderColor: "#FFFFFF",
							customRadius: 85
						}
					},
					timer: null
				},
			}
		},
		onLoad() {
			this.getInflowWater();
			console.log('页面加载');
		},
		onShow() {
			this.getNewsBanner();
			this.startTimer();
			console.log('页面显示');
		},
		onHide() {
			console.log('页面隐藏');
			this.stopTimer();
		},
		onUnload() {
			console.log('页面隐藏');
			this.stopTimer();
		},
		beforeDestroy() {
			console.log('页面隐藏');
			this.stopTimer();
		},

		methods: {
			async init() {
				const echarts = require('@/uni_modules/lime-echart/static/echarts.min');
				const [alarmChart, thingOrderChart] = await Promise.all([
					this.$refs.chartRef.init(echarts),
					this.$refs.chartRef1.init(echarts)
				]);

				this.alarmChart = alarmChart;
				this.thingOrderChart = thingOrderChart;

				this.alarmChart.setOption(this.option);
				this.thingOrderChart.setOption(this.option2);

			},

			getFormattedTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			navTo(url) {
				uni.reLaunch({
					url: "/pages/sys/index/navigavtion"
				});
				uni.removeStorageSync('navId');
			},


			handleSearchData(data) {
				this.searchData = data; // 接收到子组件传递过来的数据
				this.getKeyWater();
				//进水
				this.getInflowWater();
				//出水
				this.getOutWater();
				//图表
				this.getServerData();
				this.getThingsData();
				this.getAlarmData();

				const tabBar = uni.getStorageSync('tabBar');
				if (tabBar == 0) {
					this.showIcon = false;
				}
			},

			startTimer() {
				this.timer = setInterval(async () => {
					try {
						// 执行异步任务并等待完成
						await this.getInflowWater();
						await this.getOutWater();
						await this.getKeyWater();
						await this.getServerData();
						await this.getThingsData();
						await this.getAlarmData();
					} catch (error) {
						console.error('Error occurred during timer execution:', error);
					}
				}, 8000);
			},
			stopTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},

			getNewsBanner() {
				this.$u.api.news({
					"algorithmProcessId": "water_news_recommend",
					"param": {
						"data": {

						}
					}
				}).then(res => {
					this.swiperList = res.data.data.result.map(item => {
						return {
							id: item.id,
							image: config.adminPath + item.news_coverphoto,
							url: '/pages/sys/news/new-detail'
						};
					})
				})
			},

			getInflowWater() {
				this.$u.api.inflowWater({
					"algorithmProcessId": "waterInflowReadData",
					"param": {
						"data": {
							"structure_uuid": uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					this.inflowWater = res.data.data.result.tags.map(item => {
						return {
							title: item.tagDescribe,
							value: item.value,
							unit: item.unit,
							// imagUrl: `/static/index/waterQuality/${item.tagDescribe}.png`
							imagUrl: `/static/index/waterQuality/PH.png`
						};
					});
					this.activeSection3 = "section3";
				})

			},
			getOutWater() {
				this.$u.api.outWater({
					"algorithmProcessId": "waterEffluentReadData",
					"param": {
						"data": {
							"structure_uuid": uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					this.outWater = res.data.data.result.tags.map(item => {
						return {
							title: item.tagDescribe,
							value: item.value,
							unit: item.unit,
							// imagUrl: `/static/index/waterQuality/${item.tagDescribe}2.png`
							imagUrl: `/static/index/waterQuality/PH2.png`
						}
					})
					this.activeSection3 = "section4";
				})

			},

			getServerData() {
				this.$u.api.eqStateData({
					"algorithmProcessId": "equipment_status_network_status",
					"param": {
						"data": {
							"structure_uuid": uni.getStorageSync('navId')
						}
					}
				}).then(response => {
					let chartData = response.data.data.result.statusResult.map(item => {
						let statusMap = {
							'1': '异常',
							'2': '运行',
							'3': '停止',
							'4': '维修维护'
						};
						const statusName = statusMap[item.status];
						return {
							name: statusMap[item.status],
							value: item.status_count,
							labelShow: statusMap[item.status] === '运行',
							labelText: statusName === '运行' ? `运行: ${item.status_count} 台` : ''
						};
					});

					setTimeout(() => {
						//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
						let res = {
							series: [{
								data: chartData
							}]
						};
						this.chartData = JSON.parse(JSON.stringify(res));
					}, 100);

				})

			},

			getThingsData() {
				this.$u.api.getThingsResponse({
					"algorithmProcessId": "getThingsResponse",
					"param": {
						"data": {}
					}
				}).then(response => {
					const result = response.data.data.result;
					const okOrder = result.okOrder;
					const noOrder = result.noOrder;
					const totalValue = okOrder + noOrder;

					const okPerValue = totalValue === 0 ? "0" : ((okOrder / totalValue) * 100).toFixed(2);
					const noPerValue = totalValue === 0 ? "0" : ((noOrder / totalValue) * 100).toFixed(2);

					// 更新数据
					this.option2.series[0].data = [{
							name: `已响应       ${okOrder}    ${okPerValue}%`,
							legendname: "已响应",
							value: okOrder
						},
						{
							name: `未响应       ${noOrder}    ${noPerValue}%`,
							legendname: "未响应",
							value: noOrder
						}
					];

					this.option2.title[0].text = okOrder;
					this.thingOrderChart.setOption(this.option2);
				})
			},

			getAlarmData() {
				this.$u.api.getStationAlarmData({
					"algorithmProcessId": "getStationAlarmData",
					"param": {
						"data": {

						}
					}
				}).then(response => {
					const result = response.data.data.result
					const responseData = result.find(item => item.legendname === '已响应');
					const responseValue = responseData ? responseData.value : '0'
					const totalValue = result.reduce((sum, item) => sum + item.value, 0);

					this.option.series[0].data = result.map(item => {
						const perValue = totalValue === 0 ? "0" : ((item.value / totalValue) * 100)
							.toFixed(2);
						return {
							name: `${item.type}       ${item.value}    ${perValue}%`,
							legendname: item.type,
							value: item.value
						};
					});
					this.option.title[0].text = responseValue
					this.alarmChart.setOption(this.option);
				})

			},
			//关键指标
			getKeyWater() {
				this.formattedTime = this.getFormattedTime();
				this.$u.api.searchKey({
					"algorithmProcessId": "getStationHomeData",
					"param": {
						"data": {
							"structure_uuid": uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					if (res && res.data.data.result.home_data) {
						this.homeData = res.data.data.result.home_data
					}
				})
			},


		}
	};
</script>
<style lang="scss">
	@import '@/static/font/font.css';
	@import '@/pages/sys/index/index/styles/index.scss';
</style>